/*
 * TimeTaggerTrigger.cpp
 *
 *  Created on: 25.03.2013
 *      Author: mag
 */

#include <iostream>

#include "TimeTaggerSCPI.h"
#include "../backend/TimeTagger.h"
#include "../backend/Control.h"

/**
 * _TRIGger
 * 		:HELP
 * 		:SET
 * 			:[START] [<n>,] <ch>
 * 			:[START] [<n>,] <tm>
 * 			:[START]
 * 				:NONE
 * 			:END [<n>,] <ch>
 * 			:END [<n>,] <tm>
 * 				:NONE
 * 			:RESTART [<n>,] <ch>
 * 			:RESTART [<n>,] <tm>
 * 				:NONE
 * 		:REMOVE
 * 			:[START] [<n>]
 * 			:END [<n>]
 * 			:RESTART [<n>]
 * 		:LIST?
 *
 * INITiate
 * 		:HELP?
 * 		:[IMMEdiate] [<n>]
 * 			:ALL
 * 		:START [<n>]
 * 			:ALL
 * 		:RESTart [<n>]
 * 			:ALL
 * 		:STOP
 * 			:ALL
 *
 * :FETch? [<n>]
 * :READ? [<n>]
 *
 */
static const long MSECS_PER_SECOND=1000;

bool parse_channel(int &channel, const char *str, size_t len) {

}

static bool parse_channel_and_trigger(TimeTaggerSCPIContext * context,
		int &slot, int &channel, long &tm) {
	slot=channel=-1;
	tm=-1;

	const char *parm1, *parm2;
	size_t sz1, sz2;
	if (!SCPI_ParamString(context, &parm1, &sz1, true))
		return false;
	if (SCPI_ParamString(context, &parm2, &sz2, false)) {
		// has two arguments
		if (!SCPI_ParseParamInt(context, &slot, parm1, sz1)) {
			return false;
		}
		scpi_number_t number;
		if (SCPI_ParseParamNumber(context, &number, parm2, sz2)) {
			tm=number.value * MSECS_PER_SECOND;
		} else if (parse_channel(channel, parm2, sz2)) {
			// nil
		} else
			return false;

	} else {

	}
	return (slot>=0 && slot<=16);
}


// ::TRIGger:HELP?
scpi_result_t TimeTaggerSCPI::TRIG_HELP(TimeTaggerSCPIContext * context) {
	return SCPI_RES_OK;
}

// ::TRIGger:LIST?
scpi_result_t TimeTaggerSCPI::TRIG_LIST(TimeTaggerSCPIContext * context) {

	return SCPI_RES_OK;
}

// ::TRIGger:SET_START
scpi_result_t TimeTaggerSCPI::TRIG_SET_START(TimeTaggerSCPIContext * context) {
	int slot, channel;
	long tm;

	if (!parse_channel_and_trigger(context, slot, channel, tm))
		return SCPI_RES_ERR;

	_Iterator *it=Control::get_module_slot(channel);
	if (!it) {
		//pushError
		return SCPI_RES_ERR;
	}

	it->set_start_trigger_channel(channel);
	it->set_start_trigger_time(tm);
	return SCPI_RES_OK;
}

// ::TRIGger:SET_END
scpi_result_t TimeTaggerSCPI::TRIG_SET_END(TimeTaggerSCPIContext * context) {
	int slot, channel;
	long tm;

	if (!parse_channel_and_trigger(context,slot, channel, tm))
		return SCPI_RES_ERR;

	_Iterator *it=Control::get_module_slot(channel);
	if (!it) {
		//pushError
		return SCPI_RES_ERR;
	}

	it->set_end_trigger_channel(channel);
	it->set_end_trigger_time(tm);
	return SCPI_RES_OK;
}

// ::TRIGger:SET_RESTART
scpi_result_t TimeTaggerSCPI::TRIG_SET_RESTART(TimeTaggerSCPIContext * context) {

	return SCPI_RES_OK;
}

